#include <jni.h>
#include <string>

extern "C" {
#include "include/libavcodec/avcodec.h"
#include "include/libavformat/avformat.h"
#include "include/libavutil/imgutils.h"
#include "include/libswscale/swscale.h"
#include "include/libswresample/swresample.h"
}

#include "AndroidLog.h"
#include "MNCallJava.h"
#include "MNFFmpeg.h"
#include "MNPlaystatus.h"


JavaVM *javaVM = NULL;

extern "C"
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    jint result = -1;
    javaVM = vm;
    JNIEnv *env;
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_4) != JNI_OK) {
        return result;
    }
    return JNI_VERSION_1_4;
}


MNCallJava *callJava = NULL;
MNFFmpeg *fFmpeg = NULL;
MNPlaystatus *playstatus = NULL;

bool noExiting= true;

//初始化FFMPEG
extern "C"
JNIEXPORT void JNICALL
Java_com_yfjin_ffmpeg54_player_MNPlayer_native_1prepare(JNIEnv *env, jobject thiz,
                                                        jstring _source) {

    const char *source = env->GetStringUTFChars(_source, 0);

    if (fFmpeg == NULL) {
        if (callJava == NULL) {
            callJava = new MNCallJava(javaVM, env, &thiz);
        }
        playstatus = new MNPlaystatus();
        fFmpeg = new MNFFmpeg(playstatus, callJava, source);
        fFmpeg->parpared();
    }

    env->ReleaseStringUTFChars(_source, source);
}


extern "C"
JNIEXPORT void JNICALL
Java_com_yfjin_ffmpeg54_player_MNPlayer_native_1start(JNIEnv *env, jobject thiz) {

    if (fFmpeg != NULL) {
        fFmpeg->start();
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yfjin_ffmpeg54_player_MNPlayer_native_1seek(JNIEnv *env, jobject thiz, jint second) {
    if (fFmpeg != NULL) {
        fFmpeg->seek(second);
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yfjin_ffmpeg54_player_MNPlayer_native_1pause(JNIEnv *env, jobject thiz) {
    if (fFmpeg != NULL) {
        fFmpeg->pause();
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yfjin_ffmpeg54_player_MNPlayer_native_1resume(JNIEnv *env, jobject thiz) {
    if (fFmpeg != NULL) {
        fFmpeg->resume();
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yfjin_ffmpeg54_player_MNPlayer_native_1mute(JNIEnv *env, jobject thiz, jint i) {
    if (fFmpeg != NULL) {
        fFmpeg->setMute(i);
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yfjin_ffmpeg54_player_MNPlayer_native_1speed(JNIEnv *env, jobject thiz, jfloat speed) {
    if (fFmpeg != NULL) {
        fFmpeg->setSpeed(speed);
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yfjin_ffmpeg54_player_MNPlayer_native_1pitch(JNIEnv *env, jobject thiz, jfloat i) {
    if (fFmpeg != NULL) {
        fFmpeg->setPitch(i);
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yfjin_ffmpeg54_player_MNPlayer_native_1stop(JNIEnv *env, jobject thiz) {
    if (!noExiting){
        return;
    }

    noExiting= true;
    if (fFmpeg!=NULL){
        fFmpeg->release();
        delete(fFmpeg);
        fFmpeg=NULL;
    }
}